package com.itlong.cloud.intercept.sdkV1;

import com.itlong.cloud.POJO.DTO.app.old.AppOldUserInfoDto;
import com.itlong.cloud.POJO.VO.sdk.SDKServerUserCacheVO;
import com.itlong.cloud.POJO.VO.sdk.old.SDKAppOldUserInfoCacheVO;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.enumerate.oldapp.Code;
import com.itlong.cloud.enumerate.oldapp.Message;
import com.itlong.cloud.user.app.IAppOldRegisterServiceClient;
import com.itlong.cloud.user.sdk.ISDKAppOldUserServiceClient;
import com.itlong.cloud.user.sdk.ISDKServerOldUserServiceClient;
import com.itlong.cloud.utils.date.DateUtil;
import com.itlong.cloud.utils.words.StringHandlerUtil;
import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * <desc>
 *      SDK登录拦截器
 * </desc>
 *
 * @createDate 2017/10/17
 */
@Aspect
@Component
public class SDKLoginInterceptor {

    //拦截点
    @Pointcut("execution(* com.itlong.cloud.controller.sdkV1.old..*.*(..))")
    public void excudeService(){}

    //需要排除拦截的方法
    @Value("${"+ PlatformConstants.SDK_USER_TOKEN_DONTINTERCEPT+"}")
    String dontIntercept;

    //SDK拦截模式
    @Value("${"+ PlatformConstants.SDK_LOGIN_INTECEPT_MODE+"}")
    String inteceptMode;

    @Autowired
    ISDKServerOldUserServiceClient iSDKUserServiceClient;

    @Autowired
    ISDKAppOldUserServiceClient isdkAppOldUserServiceClient;  //APP SDK用户服务接口

    @Autowired
    IAppOldRegisterServiceClient iAppOldRegisterServiceClient;

    /**
     * <desc>
     *      在切面处excudeService 做拦截处理 为了防止拦截后token失效 采用Around
     * <desc/>
     * @param
     * @return
     * @author Biao.R
     * @createDate 2017/10/17
     */
    @Around("excudeService()")
    public Object sdkInterceptor(ProceedingJoinPoint thisJoinPoint) throws Throwable {
        if (!"devTest".equals(inteceptMode.trim())) {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            //获取目标方法全路径
            String mwthodName = thisJoinPoint.getSignature().getName();
            String[] notInterceptMethods = StringHandlerUtil.splitString(dontIntercept);
            //循环配置不需要拦截的方法(登录接口未拦截)
            for (String method : notInterceptMethods) {
                method = method.replaceAll("\\*", "");
                if (mwthodName.contains(method)) {
                    return thisJoinPoint.proceed();
                }
            }
            String appid = request.getParameter("appid");
            String token = request.getParameter("token");
//            while (token.indexOf(" ") >= 0){
//                token = token.replace(" ","+");
//            }
            token = token.replaceAll(" ","+");
            String phoneNo = request.getParameter("phoneNo");

            //
            String userPhone = request.getParameter("userPhone");
            String appsecret = request.getParameter("appsecret");
            if (StringUtils.isBlank(phoneNo) && StringUtils.isNotBlank(userPhone) && StringUtils.isNotBlank(appsecret)){
                phoneNo = userPhone;
            }
            if (StringUtils.isBlank(appid) || StringUtils.isBlank(token)) {
                return new Message(Code.TOKEN_ERR);
            }
            //测试拦截效果，后期去掉
            //System.out.println("SDK拦截器：" + DateUtil.getCurrentTime() + "-IP-" + request.getRemoteAddr() + "-appid-" + appid + "-token-" + token + "-uri-" + request.getRequestURI());
            //校验token
            //不拦截登录接口
            if (StringUtils.isNotEmpty(phoneNo) && StringUtils.isNotEmpty(appid) && StringUtils.isNotEmpty(token)) {
                //当phoneNo、appid、token均不为空时，进行APP SDK拦截校验（校验Token）
                SDKAppOldUserInfoCacheVO sdkAppUserInfoCacheVO = isdkAppOldUserServiceClient.getSDKAppCacheUser(appid, phoneNo);
                if (sdkAppUserInfoCacheVO != null && StringHandlerUtil.compareStrWithOutEmpty(token, sdkAppUserInfoCacheVO.getToken())) {
                    return thisJoinPoint.proceed();
                }
                AppOldUserInfoDto userInfo = iAppOldRegisterServiceClient.selectDtoByPhone(phoneNo);
                if (userInfo == null) {
                    return new Message(Code.NOT_FOUNDUSER);
                }

                if (!StringHandlerUtil.compareStrWithOutEmpty(token, userInfo.getToken())) {
                    return new Message(Code.TOKEN_ERR);
                }

                //保存更新到缓存
                this.saveUserInfoToCache(userInfo, appid);

                return thisJoinPoint.proceed();

            } else if (StringUtils.isNotEmpty(appid) && StringUtils.isNotEmpty(token)) {
                //当appid、token均不为空时，进行APP SDK拦截校验（校验Token）
                //服务端拦截校验
                SDKServerUserCacheVO cacheUser = iSDKUserServiceClient.checkSDKCacheUser(appid, token);
                if (cacheUser != null) {
                    return thisJoinPoint.proceed();
                }
            } else {
                return new Message(Code.NOT_PARAM);
            }
            return new Message(Code.TOKEN_ERR);

        } else {
            return thisJoinPoint.proceed();
        }
    }



    /**
    * <desc>
    *    更新APP-SDK用户信息缓存.
    * </desc>
    *
    * @param userInfo 查询到的手机APP用户信息
     * @appId 引用接入凭证
    * @return xx
    * @author LewisLouis
    * @createDate 2017-11-13
    */
    private void saveUserInfoToCache(AppOldUserInfoDto userInfo, String appid)
    {
        Date now = new Date();
        String nowTimeStr = DateUtil.fomatDate(now,"yyyy-MM-dd HH:mm:ss");
        Integer expiresIn = 7 * 24 * 60 * 60;
        String invalidTime =  (DateUtil.fomatDate(DateUtil.addCurrentTime(7),"yyyy-MM-dd HH:mm:ss"));
        SDKAppOldUserInfoCacheVO sdkAppCacheUser = new SDKAppOldUserInfoCacheVO();
        sdkAppCacheUser.setUserId(userInfo.getUserId());
        sdkAppCacheUser.setUserName(userInfo.getUserName());
        sdkAppCacheUser.setPhoneNo(userInfo.getUserPhone());
        sdkAppCacheUser.setToken(userInfo.getToken());
        sdkAppCacheUser.setAppid(appid);
        sdkAppCacheUser.setExpiresIn(expiresIn);
        sdkAppCacheUser.setCreateTime(nowTimeStr);
        sdkAppCacheUser.setInvalidTime(invalidTime);
        isdkAppOldUserServiceClient.saveSDKAppCacheUser(sdkAppCacheUser);
    }


}